<template>
  <view>
    <!-- #ifdef MP-WEIXIN -->
    <!-- 圆形图标风格 -->
    <button 
      v-if="type === 'icon'" 
      open-type="getPhoneNumber" 
      @getphonenumber="onGetPhoneNumber"
      :disabled="disabled || loading"
      :class="['wechat-icon-auth', customClass]"
      hover-class="icon-hover"
    >
      <view class="wechat-icon-wrapper">
        <u-icon name="weixin-fill" size="40" color="#ffffff" class="wechat-icon"></u-icon>
      </view>
      <text class="icon-text">{{ loading ? '授权中...' : text }}</text>
    </button>

    <!-- 绿色按钮风格 -->
    <button 
      v-else-if="type === 'button'"
      open-type="getPhoneNumber" 
      @getphonenumber="onGetPhoneNumber"
      :disabled="disabled || loading"
      :class="['wechat-btn-auth', customClass]"
      hover-class="btn-hover"
    >
      <u-icon name="weixin-fill" size="40" color="#ffffff" class="wechat-btn-icon"></u-icon>
      <text>{{ loading ? '登录中...' : text }}</text>
    </button>
    <!-- #endif -->

    <!-- #ifndef MP-WEIXIN -->
    <!-- 非微信小程序环境显示普通按钮 -->
    <view :class="type === 'icon' ? 'wechat-icon-auth' : 'wechat-btn-auth'" @click="handleH5Login">
      <u-icon v-if="type === 'button'" name="weixin-fill" size="40" color="#ffffff" class="wechat-btn-icon"></u-icon>
      <text>{{ type === 'icon' ? text : (loading ? '登录中...' : text) }}</text>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import api from '@/api'
import { saveLoginInfo } from '@/api/auth.js'

export default {
  name: 'WechatPhoneAuth',
  props: {
    // UI类型：icon=圆形图标, button=绿色按钮
    type: {
      type: String,
      default: 'button',
      validator: (value) => ['icon', 'button'].includes(value)
    },
    // 按钮文字
    text: {
      type: String,
      default: '微信手机号快捷登录'
    },
    // 自定义样式类名
    customClass: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      openid: '',
      unionid: '',
      userIp: '',
      latitude: '',
      longitude: ''
    }
  },
  mounted() {
    this.initializeLocation()
  },
  methods: {
    // 初始化位置信息
    initializeLocation() {
      // 获取用户IP和位置信息
      this.userIp = '127.0.0.1' // 默认值，实际项目中需要获取真实IP
      this.latitude = '0'
      this.longitude = '0'
    },


    // H5环境微信登录
    handleH5Login() {
      this.$emit('h5Login')
    },

    // 微信小程序获取手机号授权
    async onGetPhoneNumber(e) {
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        this.$emit('error', '用户拒绝授权或授权失败')
        return
      }

      if (!e.detail.code) {
        this.$emit('error', '获取手机号授权码失败')
        return
      }

      this.loading = true
      this.$emit('loading', true)

      try {
        // 1. 先获取 openid 和 unionid
        const loginRes = await this.getWxLoginCode()
        const openidResult = await api.wechatApi.getOpenidForMiniProgram({
          code: loginRes.code
        })

        if (openidResult.r !== 0) {
          throw new Error(openidResult.msg || '获取openid失败')
        }

        this.openid = openidResult.data.openid
        this.unionid = openidResult.data.unionid

        // 2. 获取手机号
        const phoneResult = await api.wechatApi.getPhoneNumberForMiniProgram({
          code: e.detail.code
        })
        
        if (phoneResult.r !== 0) {
          throw new Error(phoneResult.msg || '获取手机号失败')
        }

        if (!phoneResult.data) {
          throw new Error('获取手机号失败：返回数据为空')
        }
        
        // 尝试多种可能的数据结构
        let mobile = null
        
        if (phoneResult.data.phone_info && phoneResult.data.phone_info.phoneNumber) {
          mobile = phoneResult.data.phone_info.phoneNumber
        } else if (phoneResult.data.phoneNumber) {
          mobile = phoneResult.data.phoneNumber
        } else if (phoneResult.data.phone) {
          mobile = phoneResult.data.phone
        } else if (phoneResult.data.mobile) {
          mobile = phoneResult.data.mobile
        } else {
          throw new Error('返回数据中未找到手机号字段')
        }

        if (!mobile) {
          throw new Error('手机号为空')
        }

        // 3. 调用登录接口（type=4 微信登录）
        const loginResult = await api.authApi.login({
          unionid: this.unionid,
          openid: this.openid,
          mobile: mobile,
          login_ip: this.userIp,
          type: 4,
          salt: '1234',
          latitude: this.latitude,
          longitude: this.longitude
        })

        if (loginResult.r === 0) {
          // 检查是否有特殊操作需要执行
          const action = loginResult.data && loginResult.data.action
          
          if (action === 'bind_phone') {
            // 需要绑定手机号
            this.$emit('bindPhone', {
              openid: this.openid,
              unionid: this.unionid,
              mobile: mobile
            })
          } else if (action === 'regist') {
            // 需要注册
            this.$emit('register', {
              openid: this.openid,
              unionid: this.unionid,
              mobile: mobile
            })
          } else {
            // 登录成功，保存用户信息
            // loginResult.data 直接就是用户信息对象，包含 token 等字段
            const userInfo = loginResult.data
            
            // 使用 saveLoginInfo 统一保存登录信息
            saveLoginInfo(userInfo, userInfo.token)
            
            this.$emit('success', userInfo)
          }
        } else {
          throw new Error(loginResult.msg || '登录失败')
        }

      } catch (error) {
        this.$emit('error', error.message || '登录失败，请重试')
      } finally {
        this.loading = false
        this.$emit('loading', false)
      }
    },

    // 获取微信登录code
    getWxLoginCode() {
      return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        wx.login({
          success: (res) => {
            if (res.code) {
              resolve(res)
            } else {
              reject(new Error('获取微信登录code失败'))
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
        // #endif
        // #ifndef MP-WEIXIN
        reject(new Error('非微信小程序环境'))
        // #endif
      })
    },

  }
}
</script>

<style lang="scss" scoped>
/* 圆形图标风格 */
.wechat-icon-auth {
  background: transparent !important;
  border: none !important;
  padding: 0 !important;
  margin: 40rpx 0 !important;
  display: flex !important;
  flex-direction: column !important;
  justify-content: center !important;
  align-items: center !important;
  width: auto !important;
  height: auto !important;

  &.icon-hover {
    background: transparent !important;
    opacity: 0.8;
  }

  .wechat-icon-wrapper {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #07c160;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
  }

  .icon-text {
    font-size: 28rpx;
    color: #000000;
  }

  &:disabled {
    .icon-text {
      color: #cccccc;
    }
  }
}

/* 移除button默认样式 */
.wechat-icon-auth::after {
  border: none !important;
}

/* 绿色按钮风格 */
.wechat-btn-auth {
  width: 400rpx;
  height: 88rpx;
  background: #13d151;
  border-radius: 8rpx;
  border: none;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20rpx auto;
  padding: 0 30rpx;

  .wechat-btn-icon {
    margin-right: 16rpx;
  }

  text {
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 500;
  }

  &.btn-hover {
    background: #11c04a;
    opacity: 0.9;
  }

  &:disabled {
    background: #cccccc;
    
    .wechat-btn-icon {
      opacity: 0.5;
    }
    
    text {
      color: #999999;
    }
  }
}

/* 非微信小程序环境样式 */
/* #ifndef MP-WEIXIN */
.wechat-icon-auth,
.wechat-btn-auth {
  cursor: pointer;
  
  &:hover {
    opacity: 0.8;
  }
}
/* #endif */
</style>
